package com.xca.znb.view;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.bumptech.glide.Glide;
import com.xca.znb.R;
import com.xca.znb.contact.MineContact;
import com.xca.znb.entity.User;
import com.xca.znb.model.impl.MineModelImpl;
import com.xca.znb.presenter.MinesPresenter;

public class MineFragment extends Fragment implements View.OnClickListener , MineContact {
    private MinesPresenter minesPresenter ;
    private View mine_fragment ;
    private ImageButton MineSettingBtn ;
    private TextView MineUserId , MineUserName , MineCouponsNumber , MineBalanceNumber , MineGoldNumber;
    private LinearLayout   MinesBalanceClick , PerMsgClick;
    private LinearLayout shoppingCart , collection , footprint , toBeShipped
            , toBeReceived , toBeEvaluated , afterSales ;
    private TextView allOrders ;
    private ImageView userAvatar ;



    private Handler handler = new Handler(Looper.getMainLooper());
    private Runnable refreshTask = new Runnable() {
        @Override
        public void run() {
            // 这里放置你需要刷新的操作
            updateUI();

            // 重新调度任务，实现每隔3秒执行一次
            handler.postDelayed(this, 300); // 3000毫秒 = 3秒
        }
    };


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (mine_fragment == null){
            mine_fragment = inflater.inflate(R.layout.mines , container , false);
        }
        MineModelImpl mineModel = new MineModelImpl(getActivity());
        minesPresenter = new MinesPresenter(this , mineModel);

        MineUserId = mine_fragment.findViewById(R.id.mine_user_id);
        MineUserName = mine_fragment.findViewById(R.id.mine_user_name);
        MineSettingBtn = mine_fragment.findViewById(R.id.mine_setting_btn);
        MineCouponsNumber = mine_fragment.findViewById(R.id.coupons_number);
        MineBalanceNumber = mine_fragment.findViewById(R.id.balance_number);
        MineGoldNumber = mine_fragment.findViewById(R.id.gold_number);
        MinesBalanceClick = mine_fragment.findViewById(R.id.balance);
        PerMsgClick = mine_fragment.findViewById(R.id.per_msg_click) ;
        allOrders = mine_fragment.findViewById(R.id.allOrders);
        shoppingCart = mine_fragment.findViewById(R.id.shopping_cart);
        collection = mine_fragment.findViewById(R.id.collection) ;
        footprint = mine_fragment.findViewById(R.id.footPrint) ;
        toBeShipped = mine_fragment.findViewById(R.id.to_be_shipped) ;
        toBeReceived = mine_fragment.findViewById(R.id.to_be_received) ;
        toBeEvaluated = mine_fragment.findViewById(R.id.to_be_evaluated) ;
        afterSales = mine_fragment.findViewById(R.id.after_sales) ;
        userAvatar = mine_fragment.findViewById(R.id.mine_user_avatar) ;

        //前往足迹页面
        footprint.setOnClickListener(this);


        minesPresenter.onMineAllOrdersClick();
        onMineToBeShippedClick();
        minesPresenter.nMineToBeReceivedClick();
        minesPresenter.nMineToBeEvaluatedClick();
        minesPresenter.onMIneAfterSalesClick();
        onToSettingButtonClick();
        onMineBalanceClick();
        collection.setOnClickListener(this);
        shoppingCart.setOnClickListener(this);

        SharedPreferences sharedPreferences = getActivity().getSharedPreferences("loginPhone", Context.MODE_PRIVATE);
        String phone = sharedPreferences.getString("phone" , "");
        MineUserId.setText(phone);
       minesPresenter.showMessage(phone);

        double account = minesPresenter.showNum(phone);
        String loginAccount = String.valueOf(account);
        MineBalanceNumber.setText(loginAccount);

        User user = minesPresenter.getUserByPhone(phone);
        if (user != null){
            String imgPath = user.getConcern();
//            Toast.makeText(getActivity(), imgPath, Toast.LENGTH_SHORT).show();
            if (imgPath==null){
                userAvatar.setImageResource(R.drawable.mine_b);
            }else {
                Uri uri = Uri.parse(imgPath);
               // getActivity().getApplicationContext().getContentResolver().takePersistableUriPermission(uri,Intent.FLAG_GRANT_READ_URI_PERMISSION);
                Glide.with(this)
                        .load(imgPath)
                        .into(userAvatar);
            }

        }

        PerMsgClick.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity() , PersonalCenter.class) ;
                startActivity(intent);
            }
        });

        startPeriodicRefresh();

        return mine_fragment ;
    }


    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.mine_setting_btn){
            Intent intent = new Intent(getActivity() , Setting.class);
            startActivity(intent);
        } else if (v.getId() == R.id.balance) {
            Intent intent = new Intent(getActivity() , MyAssetsActivity.class);
            startActivity(intent);
        } else if (v.getId() == R.id.footPrint) {
            Intent intent = new Intent(getActivity() , FootprintActivity.class) ;
            startActivity(intent);
        } else if (v.getId() == R.id.allOrders) {
            Intent intent = new Intent(getActivity() , OrdersActivity.class);
            intent.putExtra("case", 1);
            startActivity(intent);
        }else if (v.getId() == R.id.to_be_shipped) {
            Intent intent = new Intent(getActivity() , OrdersActivity.class);
            intent.putExtra("case", 2);
            startActivity(intent);
        }else if (v.getId() == R.id.to_be_received) {
            Intent intent = new Intent(getActivity() , OrdersActivity.class);
            intent.putExtra("case", 3);
            startActivity(intent);
        }else if (v.getId() == R.id.to_be_evaluated) {
            Intent intent = new Intent(getActivity() , OrdersActivity.class);
            intent.putExtra("case", 4);
            startActivity(intent);
        }else if (v.getId() == R.id.after_sales) {
            Intent intent = new Intent(getActivity() , OrdersActivity.class);
            intent.putExtra("case", 5);
            startActivity(intent);
        } else if (v.getId() == R.id.collection) {
            Intent intent = new Intent(getActivity() , CollectionActivity.class);
            startActivity(intent);
        } else if (v.getId() == R.id.shopping_cart) {
           Intent intent = new Intent(getActivity() , ShoppingCartActivity.class);
           startActivity(intent);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        SharedPreferences sharedPreferences = getActivity().getSharedPreferences("loginPhone", Context.MODE_PRIVATE);
        String phone = sharedPreferences.getString("phone" , "");
        minesPresenter.showMessage(phone);
        User user = minesPresenter.getUserByPhone(phone);
        String imgPath = user.getConcern();
        Glide.with(getActivity())
                .load(imgPath)
                .into(userAvatar);
    }

    @Override
    public void onMineUserAvatarShow(String avatarPath) {
        ImageView avatar = mine_fragment.findViewById(R.id.mine_user_avatar);
        if (avatarPath.equals("mine_b.png")){
            avatar.setImageResource(R.drawable.mine_b);
        }else {
            try {
                Bitmap bitmap = BitmapFactory.decodeFile(avatarPath);
                avatar.setImageBitmap(bitmap);
            }catch (Exception e){
                avatar.setImageResource(R.drawable.mine_b);
            }
        }
    }

    @Override
    public void onMineUserIdShow(String userId) {
    }

    @Override
    public void onMineUserNameShow(String userName) {
        MineUserName.setText(userName);
    }

    @Override
    public void onToSettingButtonClick() {
        MineSettingBtn.setOnClickListener(this);
    }

    @Override
    public void onMineShoppingCartClick() {

    }

    @Override
    public void onMineCollectionClick() {

    }

    @Override
    public void onMineFootPrintClick() {

    }

    @Override
    public void onMineAllOrdersClick() {
        allOrders.setOnClickListener(this);
    }

    @Override
    public void onMineToBeShippedClick() {
        toBeShipped.setOnClickListener(this);
    }

    @Override
    public void onMineToBeReceivedClick() {
        toBeReceived.setOnClickListener(this);
    }

    @Override
    public void onMineToBeEvaluatedClick() {
        toBeEvaluated.setOnClickListener(this);
    }

    @Override
    public void onMIneAfterSalesClick() {
        afterSales.setOnClickListener(this);
    }

    @Override
    public void onMineCouponsClick() {

    }

    @Override
    public void onMineBalanceClick() {
        MinesBalanceClick.setOnClickListener(this);
    }

    @Override
    public void onMineGoldClick() {

    }

    @Override
    public void onMineCouponsNumberSet(Double couponsNumber) {
        MineCouponsNumber.setText(couponsNumber.toString());
    }

    @Override
    public void onMineBalanceNumberSet(Double balanceNumber) {

//        SharedPreferences sharedPreferences = getActivity().getSharedPreferences("loginPhone", Context.MODE_PRIVATE);
//        String phone = sharedPreferences.getString("phone" , "");
//        double account = minesPresenter.showNum(phone);
//        String loginAccount = String.valueOf(account);
//        MineBalanceNumber.setText(loginAccount);
    }

    @Override
    public void onMineGoldNumberSet(Double goldNumber) {
        MineGoldNumber.setText(goldNumber.toString());
    }

    @Override
    public void displayData(User user) {
        MineUserId.setText(user.getName());
        MineUserName.setText(user.getPhone());

    }



    @Override
    public void onDestroy() {
        super.onDestroy();

        // 页面销毁时，取消定时任务，防止内存泄漏
        stopPeriodicRefresh();
    }

    private void startPeriodicRefresh() {
        handler.post(refreshTask);
    }

    private void stopPeriodicRefresh() {
        handler.removeCallbacksAndMessages(null);
    }

    private void updateUI() {
        SharedPreferences sharedPreferences = getActivity().getSharedPreferences("loginPhone", Context.MODE_PRIVATE);
        String phone = sharedPreferences.getString("phone" , "");
        MineUserId.setText(phone);
        minesPresenter.showMessage(phone);

        double account = minesPresenter.showNum(phone);
        String loginAccount = String.valueOf(account);
        MineBalanceNumber.setText(loginAccount);
    }
}
